package com.yt.product.server.api.cms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import com.yt.product.models.service.IInsuranceProductService;
import com.yt.product.models.bo.InsuranceProductSaveBO;
import com.yt.product.models.bo.InsuranceProductBO;
import com.yt.product.models.dto.InsuranceProductDTO;
import com.yt.product.models.entity.InsuranceProduct;
import com.yt.product.server.utils.InsuranceProductConverter;
import java.math.BigDecimal;

/**
 * 保险产品表控制器
 *
 * @author yuanxinwen
 * @Date 2025-10-30 16:12:52
 */

@RestController
@RequestMapping("/cms/insuranceProduct")
@Slf4j
@Api(value = "InsuranceProductController",tags = "保险产品表接口")
public class InsuranceProductController {

    @DubboReference(interfaceClass = IInsuranceProductService.class, check = false, timeout = 10000, retries = 0)
    private IInsuranceProductService insuranceProductService;

    @ApiOperation(value = "添加保险产品表",notes = "添加保险产品表")
    @PostMapping(value = "/insert")
    public Result insert(InsuranceProductSaveBO saveBO) {
        try {
            // 参数验证
            if (saveBO == null) {
                return new Result<>(CodeEnum.FAIL_100002);
            }
            
            if (saveBO.getProductName() == null || saveBO.getProductName().trim().isEmpty()) {
                return new Result<>(CodeEnum.FAIL_100002.getCode(), "产品名称不能为空");
            }
            
            boolean flag = insuranceProductService.add(saveBO);
            if (flag){
                return new Result<>();
            } else {
                return new Result<>(CodeEnum.FAIL_100007.getCode(), "保存保险产品失败");
            }
        } catch (Exception e) {
            log.error("添加保险产品时发生异常: ", e);
            // 检查是否是唯一性约束违反异常
            if (e instanceof java.sql.SQLIntegrityConstraintViolationException || 
                (e.getCause() != null && e.getCause() instanceof java.sql.SQLIntegrityConstraintViolationException) ||
                (e.getMessage() != null && e.getMessage().contains("Duplicate entry"))) {
                if ((e.getMessage() != null && e.getMessage().contains("uk_product_name")) ||
                    (e.getCause() != null && e.getCause().getMessage() != null && e.getCause().getMessage().contains("uk_product_name"))) {
                    return new Result<>(CodeEnum.FAIL_100007.getCode(), "保险产品名称已存在，请使用其他名称");
                } else {
                    return new Result<>(CodeEnum.FAIL_100007.getCode(), "保存保险产品失败，数据违反唯一性约束");
                }
            }
            return new Result<>(CodeEnum.FAIL_100005);
        }
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存保险产品表",notes = "保存保险产品表")
    public Result save(@RequestBody InsuranceProductSaveBO saveBO){
        System.out.println("=== 保存保险产品 ===");
        System.out.println("接收到的saveBO数据: " + saveBO);
        
        try {
            if(saveBO.getProductId() == null){
                //添加
                System.out.println("执行添加操作");
                return insert(saveBO);
            } else {
                System.out.println("执行更新操作");
                return update(saveBO);
            }
        } catch (Exception e) {
            log.error("保存保险产品时发生异常: ", e);
            return new Result<>(CodeEnum.FAIL_100005);
        }
    }

    @ApiOperation(value = "修改保险产品表",notes = "修改保险产品表")
    @PostMapping("/update")
    public Result update(@RequestBody InsuranceProductSaveBO saveBO){
        System.out.println("=== 更新保险产品 ===");
        System.out.println("接收到的saveBO数据: " + saveBO);
        
        try {
            // 参数验证
            if (saveBO == null || saveBO.getProductId() == null) {
                return new Result<>(CodeEnum.FAIL_100002);
            }
            
            InsuranceProduct entity = new InsuranceProduct();
            
            // 手动映射字段，避免BeanUtils可能的问题
            // 严格按照前端传入的数据进行处理，不设置任何默认值
            entity.setProductId(saveBO.getProductId());
            entity.setProductName(saveBO.getProductName());
            entity.setTypeAttrId(saveBO.getTypeAttrId());
            entity.setMinAmount(saveBO.getMinAmount());
            entity.setMaxAmount(saveBO.getMaxAmount());
            entity.setMinTerm(saveBO.getMinTerm());
            entity.setMaxTerm(saveBO.getMaxTerm());
            entity.setPayRatio(saveBO.getPayRatio());
            entity.setDescription(saveBO.getDescription());
            entity.setStatus(saveBO.getStatus());
            entity.setIsDelete(saveBO.getIsDelete());
            
            System.out.println("准备更新的Entity数据: " + entity);
            
            boolean flag = insuranceProductService.updateById(entity);
            if (flag){
                System.out.println("更新成功");
                return new Result<>();
            } else {
                System.out.println("更新失败");
                return new Result<>(CodeEnum.FAIL_100008);
            }
        } catch (Exception e) {
            log.error("更新保险产品时发生异常: ", e);
            return new Result<>(CodeEnum.FAIL_100005);
        }
    }

    @PostMapping("/updateStatus")
    @ApiOperation(value = "修改状态",notes = "修改状态")
     @ApiImplicitParams({
             @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
             ,@ApiImplicitParam(name = "status",value = "产品状态（0=下架，1=上架）",required = true,paramType = "query", dataType = "Integer")
     })
     public Result updateStatus(@RequestParam(value = "id", required = false) Long id, @RequestParam(value = "status", required = false) Integer status){
         try {
             // 检查参数是否存在
             if (id == null || status == null) {
                 return new Result<>(CodeEnum.FAIL_100002);
             }
             InsuranceProduct entity = new InsuranceProduct();
             entity.setProductId(id.intValue()); // 使用productId作为主键
             entity.setStatus(status);
            boolean flag = insuranceProductService.updateById(entity);
             if(flag){
                 return new Result<>();
             } else {
                 return new Result<>(CodeEnum.FAIL_100008);
             }
         } catch (Exception e) {
             log.error("更新保险产品状态时发生异常: ", e);
             return new Result<>(CodeEnum.FAIL_100005);
         }
     }

    @ApiOperation(value = "删除保险产品表",notes = "删除保险产品表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "保险产品表id", required = false, paramType = "query", dataType = "Long"),
        @ApiImplicitParam(name = "productId", value = "保险产品表id", required = false, paramType = "query", dataType = "Long")
    })
    @PostMapping("/delete")
    public Result delete(@RequestParam(value = "id", required = false) Long id, 
                         @RequestParam(value = "productId", required = false) Long productId,
                         @RequestBody(required = false) InsuranceProductSaveBO saveBO){
        try {
            // 检查参数是否存在，优先使用id，如果没有则使用productId
            Long productIdValue = (id != null) ? id : productId;
            // 如果通过请求体传递了数据，则从中获取productId
            if (productIdValue == null && saveBO != null && saveBO.getProductId() != null) {
                productIdValue = Long.valueOf(saveBO.getProductId());
            }
            if (productIdValue == null) {
                return new Result<>(CodeEnum.FAIL_100002);
            }
            // 使用逻辑删除而不是物理删除
            InsuranceProduct entity = new InsuranceProduct();
            entity.setProductId(productIdValue.intValue()); // 使用productId作为主键
            entity.setIsDelete(1); // 设置为已删除状态
            boolean flag = insuranceProductService.updateById(entity);
            if (flag){
                return new Result<>();
            } else {
                return new Result<>(CodeEnum.FAIL_100009);
            }
        } catch (Exception e) {
            log.error("删除保险产品时发生异常: ", e);
            return new Result<>(CodeEnum.FAIL_100005);
        }
    }

    @PostMapping("/deleteBatch")
    @ApiOperation(value = "批量删除保险产品表",notes = "批量删除保险产品表")
    @ApiImplicitParam(name = "ids",value = "ids:以逗号隔开",required = true,paramType = "query", dataType = "String")
    public Result deleteBatch(@RequestParam(value = "ids", required = false) String ids){
        try {
            if(StrUtils.isEmpty(ids)){
                return new Result(CodeEnum.FAIL_100002 );
            }
            String[] arr = ids.split(",");
            List<Long> idList = Arrays.stream(arr)
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            insuranceProductService.removeByIds(idList);
            return new Result<>();
        } catch (Exception e) {
            log.error("批量删除保险产品时发生异常: ", e);
            return new Result<>(CodeEnum.FAIL_100005);
        }
    }

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<InsuranceProductDTO> get(@RequestParam(value = "id", required = false) Long id){
        try {
            if(id == null){
                return new Result<>(CodeEnum.FAIL_100002 );
            }

            InsuranceProduct entity = insuranceProductService.getById(id);
            InsuranceProductDTO dto = InsuranceProductConverter.entityToDTO(entity);

            return new Result<>(dto);
        } catch (Exception e) {
            log.error("查询保险产品详情时发生异常: ", e);
            return new Result<>(CodeEnum.FAIL_100005);
        }
    }

    @ApiOperation(value = "保险产品表列表",notes = "保险产品表列表")
    @PostMapping("/queryPageList")
    public Result<Page<InsuranceProductDTO>> queryPageList(@RequestBody InsuranceProductBO bo){
        try {
            QueryWrapper<InsuranceProduct> wrapper = new QueryWrapper<>();
            
            if (bo != null) {
                if (bo.getStatus() != null){
                    wrapper.eq("status", bo.getStatus());
                }
                
                if (bo.getStartDate() != null){
                    wrapper.ge("create_time", bo.getStartDate());
                }
                
                if (bo.getEndDate() != null){
                    wrapper.le("create_time", bo.getEndDate());
                }
            }
            
            // 添加只查询未删除的产品
            wrapper.eq("is_delete", 0);
            
            // 正确设置分页参数
            int pageNo = 1;
            int pageSize = 10;
            
            if (bo != null) {
                // 使用包装类型进行判断，避免空指针异常
                Integer boPageNo = bo.getPageNo();
                Integer boPageSize = bo.getPageSize();
                
                if (boPageNo != null && boPageNo > 0) {
                    pageNo = boPageNo;
                }
                if (boPageSize != null && boPageSize > 0) {
                    pageSize = boPageSize;
                }
            }
            
            // 确保分页参数合法
            if (pageNo <= 0) pageNo = 1;
            if (pageSize <= 0) pageSize = 10;
            if (pageSize > 100) pageSize = 100; // 限制最大页面大小
            
            Page<InsuranceProduct> page = new Page<>(pageNo, pageSize);
            // 添加空值检查，防止空指针异常
            if (insuranceProductService != null) {
                page = insuranceProductService.page(page, wrapper);
            } else {
                log.error("insuranceProductService is null");
                return new Result<>(CodeEnum.FAIL_100005);
            }
            
            // 转换Page<InsuranceProduct>为Page<InsuranceProductDTO>
            Page<InsuranceProductDTO> dtoPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
            // 使用stream转换并收集到新的列表中
            List<InsuranceProductDTO> dtoList = page.getRecords().stream()
                    .map(InsuranceProductConverter::entityToDTO)
                    .collect(Collectors.toList());
            dtoPage.setRecords(dtoList);

            return new Result<>(dtoPage);
        } catch (Exception e) {
            log.error("查询保险产品列表时发生异常: ", e);
            return new Result<>(CodeEnum.FAIL_100005);
        }
    }
}